package com.xdf.xzymanagementsystem.controller.system;

import com.xdf.xzymanagementsystem.entity.Computer;
import com.xdf.xzymanagementsystem.entity.EMail;
import com.xdf.xzymanagementsystem.entity.ResponseResult;
import com.xdf.xzymanagementsystem.enums.ResponseEnum;
import com.xdf.xzymanagementsystem.service.CallProcedureService;
import com.xdf.xzymanagementsystem.service.LeakService;
import com.xdf.xzymanagementsystem.service.LogSalesorderdtlfinishedService;
import com.xdf.xzymanagementsystem.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/dev")
public class DevController {
    private static final Logger logger = LoggerFactory.getLogger("logTraceId");
    @Value("${globalv.server}")
    private String server;

    @Autowired
    private Computer computer;
    @Autowired
    private LeakService leakService;
    @Autowired
    private CallProcedureService callProcedureService;
    @Autowired
    private MailUtils mailUtils;
    @Autowired
    private LogSalesorderdtlfinishedService logSalesorderdtlfinishedService;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private MybatisUtils mybatisUtils;
    @Autowired
    private CustomSqlUtils customSqlUtils;
    @Autowired
    private SystemUtils systemUtils;

    /**
     * 2021年12月3日 15:42:44 chanchaw
     * 参数 Map 类型的两个 key:
     * pks = List<Integer>
     * record = log_salesorderdtlfinished 对象
     * @param params
     * @return
     */
    @PostMapping("/logs")
    public ResponseResult<Integer> multiInsertLogs(@RequestBody Map<String,Object> params){
        return ResponseResult.<Integer>builder().success(true).message(ResponseEnum.OK.getName()).data(logSalesorderdtlfinishedService.multiInsert(params)).build();
    }

    @GetMapping("/userId")
    public ResponseResult<Integer> getUserId(){
        return ResponseResult.<Integer>builder().success(true).message(ResponseEnum.OK.getName()).data(logSalesorderdtlfinishedService.getUserId()).build();
    }

    @GetMapping("/computer")
    public ResponseResult<Computer> getComputerInfo(){
        return ResponseResult.<Computer>builder().success(true).message(ResponseEnum.OK.getName()).data(computer).build();
    }

    @GetMapping("/noPrice")
    public ResponseResult<List<Long>> getNoPrice(){
        return ResponseResult.<List<Long>>builder().success(true).message(ResponseEnum.OK.getName()).data(leakService.getDeliveryListNoPrice()).build();
    }

    @GetMapping("/2Price")
    public ResponseResult<List<Long>> get2Price(){
        return ResponseResult.<List<Long>>builder().success(true).message(ResponseEnum.OK.getName()).data(leakService.getDeliveryList2Price()).build();
    }

    /**
     * 2021年8月25日 22:32:13 chanchaw
     * 更新指定销售订单明细的单价金额
     * @param id
     * @return
     */
    @GetMapping("/updateSalesOrderDtlPrice/{id}")
    public ResponseResult<Long> updateSalesOrderDtlPrice(@PathVariable Long id){
        return ResponseResult.<Long>builder().success(true).message(ResponseEnum.OK.getName()).data(Long.valueOf(callProcedureService.updateSalesOrderDtlPrice(id))).build();
    }

    /**
     * 2021年8月25日 22:32:28 chanchaw
     * 更新指定发货计划明细数据的单价金额
     * @param id
     * @return
     */
    @GetMapping("/updateDeliveryPlanDtlPrice/{id}")
    public ResponseResult<Long> updateDeliveryPlanDtlPrice(@PathVariable Long id){
        return ResponseResult.<Long>builder().success(true).message(ResponseEnum.OK.getName()).data(Long.valueOf(callProcedureService.updateDeliveryPlanPrice(id))).build();
    }

    /**
     * 2021年8月25日 22:32:43 chanchaw
     * 更新指定成品出库明细数据的单价金额
     * @param id
     * @return
     */
    @GetMapping("/updateProductOrderDtlPrice/{id}")
    public ResponseResult<Long> updateProductOrderDtlPrice(@PathVariable Long id){
        return ResponseResult.<Long>builder().success(true).message(ResponseEnum.OK.getName()).data(Long.valueOf(callProcedureService.updateProductOrderPrice(id))).build();
    }

    @GetMapping("/updateStatementAccount/{id}")
    public ResponseResult<Long> updateStatementAccount(@PathVariable Long id){
        return ResponseResult.<Long>builder().success(true).message(ResponseEnum.OK.getName()).data(Long.valueOf(callProcedureService.updateStatementAccount(id))).build();
    }

    /**
     * 2021年8月25日 22:49:36 chanchaw
     * 更新出货一览表中所有数据的单价金额，参照当前存货档案中的单价
     * 同时修改含税单价、不含税单价
     * @return
     */
    @GetMapping("/updateDeliveryAllPrice")
    public ResponseResult<Long> updateDeliveryAllPrice(){
        return ResponseResult.<Long>builder().success(true).message(ResponseEnum.OK.getName()).data(Long.valueOf(callProcedureService.updateDeliveryAllPrice())).build();
    }

    @GetMapping("/testWechat")
    public ResponseResult<Void> testWechat(){
        List<String> list = new ArrayList<>();
        list.add("测试发送给管理员模板消息");
        list.add("");
        list.add(DatetimeUtils.formatNow());
        leakService.pushWechatTmpMsg(list);
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }

    @GetMapping("/testMail")
    public ResponseResult<Void> testMail(){
        mailUtils.sendSimpleMail("409223171@qq.com","测试发送邮件","server:"+server+",来自旭纸业项目的测试发送邮件功能");
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }

    @GetMapping("/checkDeliveryListNoPrice")
    public ResponseResult<Void> checkDeliveryListNoPrice(){
        leakService.checkDeliveryListNoPrice();
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }

    @GetMapping("/checkDeliveryList2Price")
    public ResponseResult<Void> checkDeliveryList2Price(){
        leakService.checkDeliveryList2Price();
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }

    @PostMapping("/sendDevEMail")
    public ResponseResult<Void> sendDevEMail(@RequestBody EMail eMail){
        mailUtils.sendSimpleMail(eMail.getTo(),eMail.getSubject(),eMail.getContent());
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }

    // 清除 mybatis 二级缓存数据
    @GetMapping("/showMybatisCacheL2")
    public ResponseResult<Map<Object,Object>> showMybatisCacheL2() throws NoSuchFieldException, IllegalAccessException, IOException {
        MybatisUtils mybatisUtils = new MybatisUtils("Configuration/mybatis-config.xml");
        mybatisUtils.test1(sqlSessionFactory);

        return ResponseResult.<Map<Object,Object>>builder().success(true).data(mybatisUtils.getL2Cache()).message(ResponseEnum.OK.getName()).build();
    }

//    @Bean
//    private MybatisUtils buildMybatisUtils() throws IllegalAccessException, NoSuchFieldException, IOException {
//        return new MybatisUtils("Configuration/mybatis-config.xml");
//    }


    // 以下是执行自定义SQL
    @ApiOperation(value="执行查询SQL", notes="示例：http://localhost:7075/zipperdye/dynamicQuery/querySqlString/select * from bill_type", produces="application/json")
    @GetMapping("/querySqlString/{sql}")
    public JsonResult querySqlString(@PathVariable String sql){
        return JsonResult.ok(customSqlUtils.queryForList(sql));
    }

    @ApiOperation(value="执行查询SQL", notes="示例：http://localhost:7075/zipperdye/dynamicQuery/querySqlPost。传入参数：{sql:select * from bill_type}", produces="application/json")
    @PostMapping("/querySqlPost")
    public JsonResult querySqlStringPost(@RequestBody Map<String,String> params){
        String sql = params.get("sql");
        return JsonResult.ok(customSqlUtils.queryForList(sql));
    }

    @ApiOperation(value="调用存储过程进行查询", notes="传入参数格式：[\"usp_getBillType8Storage\",\"原料仓库\"]", produces="application/json")
    @PostMapping("/callProc")
    public JsonResult callProc(@RequestBody List<String> procAndParams){
        return JsonResult.ok(customSqlUtils.queryForListCallProc(procAndParams));
    }

    @ApiOperation(value="可执行新增、修改、删除语句", notes="传入拼接了参数的SQL", produces="application/json")
    @PostMapping("/update")
    public JsonResult update(@RequestBody String sql){
        return JsonResult.ok(customSqlUtils.update(sql));
    }

    @GetMapping("/ccThreadPool")
    public JsonResult testAsync() throws InterruptedException {
        log.info("开始线程池任务");
        for(int i=0;i<20;i++){
            systemUtils.doTask1(i);
        }
        log.info("线程池任务结束");
        return JsonResult.ok("测试线程池完成");
    }

    @GetMapping("/serverTime")
    public ResponseResult<String> getServerTime(){
        String traceId = Optional.ofNullable(MDC.get("traceId")).orElse("");
        logger.info("开始使用线程池发送邮件");
        mailUtils.sendSimpleMailTraceId("409223171@qq.com","测试发送邮件","server:"+server+",获取服务器时间", traceId);
        return ResponseResult.<String>builder().success(true).message(ResponseEnum.OK.getName())
                .data(DatetimeUtils.formatNow())
                .build();
    }
}
